package http

import (
	"github.com/gin-gonic/gin"
	"strings"
	"tanbao2/config"
)

type regInfo struct {
	Method  string
	Uri     string
	Handler []gin.HandlerFunc
}

var _RegInfo []regInfo = make([]regInfo, 0, 50)

func InitNet() {
	router := gin.Default()
	router.MaxMultipartMemory = 8 << 20 // 8 MiB
	ProcessMapping(router, &_RegInfo)
	router.Run(":" + config.Config.ListenPort)
}

func RegisterHandler(method, uri string, handler ...gin.HandlerFunc) {
	info := regInfo{strings.ToUpper(method), uri, handler}
	_RegInfo = append(_RegInfo, info)
}

func ProcessMapping(mw *gin.Engine, registerInfo *[]regInfo) {
	for _, info := range *registerInfo {
		switch info.Method {
		case "GET":
			mw.GET(info.Uri, info.Handler...)
		case "POST":
			mw.POST(info.Uri, info.Handler...)
		case "PUT":
			mw.PUT(info.Uri, info.Handler...)
		case "DELETE":
			mw.DELETE(info.Uri, info.Handler...)
		case "OPTIONS":
			mw.OPTIONS(info.Uri, info.Handler...)
		}
	}
}
